﻿using NHibernate;
using NLog;
using SimpleCrypto;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Susha.Models.Helpers
{
    public static class UserRepository
    {
        private static Logger _logger = LogManager.GetCurrentClassLogger();

        public static void Save(UserClass user)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                using (ITransaction transaction = session.BeginTransaction())
                {
                    PBKDF2 simpleCrypto = new PBKDF2();
                    user.Password = simpleCrypto.Compute(user.Password);
                    user.PasswordSalt = simpleCrypto.Salt;

                    session.Save(user);
                    transaction.Commit();

                    _logger.Info(String.Format("Saved new user: {0};", user.Email));
                }
            }
        }

        public static UserClass Login(String email, String password)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                var crypto = new PBKDF2();

                UserClass user = session.QueryOver<UserClass>().Where(x => x.Email == email).SingleOrDefault();

                if (user != null && user.Password.Equals(crypto.Compute(password, user.PasswordSalt)))
                {
                    _logger.Info(String.Format("User {0} has just logged in;", user.Email));
                    return user;
                }

                return null;
            }
        }

        /// <summary>
        /// Checks whether e-mail is registered or not
        /// </summary>
        /// <param name="email">e-mail to check</param>
        /// <returns></returns>
        public static Boolean IsUserExisting(String email)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                UserClass user = session.QueryOver<UserClass>().Where(x => x.Email == email).SingleOrDefault();
                return user != null;
            }
        }
    }
}